import React from 'react';
import { Tools, Toast, Modal } from 'weaver-mobile';
import loadjs from 'loadjs'

const {getLabel} = Tools;
const alert = Modal.alert;

export default class FormSignIndex extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            // src: "http://app148.qiyuesuo.net/sign/2705982712687689870?hide_menu=true&signedByEc=1&em_client_type=mobile",
            // src: "http://127.0.0.1:8080/docs/qiyuesuo.html",
            src: "",
            nodeid: 0,
            requestid: 0
        };
    }

    componentDidMount() {
        this.registeredJs();
        this.registeredSrc();
    }

    componentWillUnMount() {
        var PMUtil = null;
        if (window && window.PostMessageUtil) {
            PMUtil = window.PostMessageUtil;
        }
        PMUtil && PMUtil.removeListener(window)
    }

    render() {
        const {src} = this.state;
        let content = null;
        if (src) {
            content = <iframe style={{border: "none"}} width={"100%"} height={"100%"} src={src}></iframe>;
        }
        return <div style={{height: "100%", width: "100%", "background-color": "#f4f4f4"}}>
            {content}
        </div>
    }

    registeredJs = () => {
        const init = () => {
            this.setState({hasLoad: true});
            const {src, requestid, nodeid} = this.state;
            //需要获取wfform
            let wfForm = null,isMobile = false, PMUtil = null;
            let wformWindow = this.getFormWindwo();
            if (wformWindow) {
                wfForm = wformWindow.wfform;
                isMobile = wfForm.isMobile()
                if (isMobile && wformWindow.rightBtn) {
                    wfForm.rightBtn = wformWindow.rightBtn;
                }
            }
            if (window && window.PostMessageUtil) {
                PMUtil = window.PostMessageUtil;
            }
            PMUtil && PMUtil.resisterListener(window, wfForm, src, function (data,autoSubmitAfterSigned, message) {
                const {code=-1} = data;
                const ua = window.navigator.userAgent;
                let ismobile = /.*E-Mobile7.*/.test(ua) || /.*E-Mobile\/7.*/.test(ua);
                if(autoSubmitAfterSigned && autoSubmitAfterSigned == 2) {
                    alert(getLabel(15172, "系统提示"), message ? message : "您已完成签署，是否提交流程？", [
                        {text:'取消', onPress: () => {}},
                        {text:'确定', onPress: () => {
                                if (ismobile && window.em && window.em.checkJsApi("postBroadcast")) {
                                    window.em.postBroadcast({
                                        name: "qysSubmitWorkflowForm",
                                        text: code
                                    });
                                    window.em.closeWindow();
                                } else {//处理云桥类
                                    wformWindow.rightBtn && wformWindow.rightBtn.doSubmitBack();//doSubmitBack
                                    window.history.go(-1);
                                }
                            }}
                        ]);
                }else {
                    if (ismobile && window.em && window.em.checkJsApi("postBroadcast")) {
                        window.em.postBroadcast({
                            name: "qysSubmitWorkflowForm",
                            text: code
                        });
                        window.em.closeWindow();
                    } else {//处理云桥类
                        wformWindow.rightBtn && wformWindow.rightBtn.doSubmitBack();//doSubmitBack
                        window.history.go(-1);
                    }
                }
            }, requestid, nodeid);
        }
        loadjs && loadjs((window.ecologyContentPath || "") + "/js/jquery/jquery_wev8.js", init);
        loadjs && loadjs((window.ecologyContentPath || "") + "/workflow/qiyuesuo/js/wf_qiyuesuoPostMessage.js", init);
    }

    registeredSrc = () =>{
        const {location = {}} = this.props;
        let {search = {}, query} = location;//默认值，签署
        if(!(query && query.url)){
            query = this.getQueryString(search) || {};
        }
        if(query && query.requestid) {
            this.setState({requestid: query.requestid});
        }
        if(query && query.nodeid) {
            this.setState({nodeid: query.nodeid});
        }
        const ua = window.navigator.userAgent;
        let ismobile = /.*E-Mobile7.*/.test(ua) || /.*E-Mobile\/7.*/.test(ua);
        let isIOS = !!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
        if (query && query.url) {//如果直接传递url解析
            if(ismobile && isIOS) {
                this.setState({src: decodeURIComponent(query.url) + "&jumpUrl=" + encodeURIComponent(window.location.protocol + "//" + window.location.host + "/spa/qiyuesuo/static4mobile/index.html#/closeWindow")});
            }else {
                this.setState({src: decodeURIComponent(query.url)});
            }
        } else {//重新去后台获取url
            let formWindow = this.getFormWindwo();
            let wfform = formWindow && formWindow.wfform || null;
            const baseInfo = wfform && wfform.getBaseInfo() || {};//获取表单默认参数，支持参数覆盖
            baseInfo.requestid && this.setState({requestid: baseInfo.requestid});
            baseInfo.nodeid && this.setState({nodeid: baseInfo.nodeid});
            query = {method: "sign", ...baseInfo, ...query}
            let options = {
                method: 'GET',
                url: (window.ecologyContentPath || "") + "/mobile/plugin/qiyuesuo/wf_qiyuesuoAjax.jsp",
                params: query
            };
            Tools.callApi(options).then(res => {
                const {url, message: msg = ""} = res;
                if (url) {
                    if(ismobile && isIOS) {
                        this.setState({src: url + encodeURIComponent(window.location.protocol + "//" + window.location.host + "/spa/qiyuesuo/static4mobile/index.html#/closeWindow")});
                    }else {
                        this.setState({src: url});
                    }
                } else {
                    Toast.error(msg, 3);
                }
            })
        }
    }

    //兼容移动端
    getFormWindwo = () => {
        let formwindow = null;
        if (!formwindow && window.opener && window.opener.wfform) {
            formwindow = window.opener
        }
        if (!formwindow && window.parent && window.parent.wfform) {
            formwindow = window.parent
        }
        if (!formwindow && window.wfform) {
            formwindow = window;
        }
        return formwindow;
    }

    getQueryString = (str) => {
        if(!str){
            return {};
        }
        const obj = {};
        str.substr(1).split('&').map(item=>{
            let arr = item.split('=');
            obj[arr[0]]=arr[1]
        })
        return obj
    }


}
